import React from 'react';
import {Button,Icon,message,Alert,Spin } from 'antd'
import {toJS} from 'mobx';
import './style/';
import {WeaTools, WeaDialog, WeaLocaleProvider} from "ecCom";
let Base64 = WeaTools.Base64;
import Setting_Tab from './Setting_Tab';
import add from './img/add.png'
import reflush from './img/reflush.png'
import lb from './img/lb.png'
const getLabel = WeaLocaleProvider.getLabel;
class Dbgz extends React.Component {


constructor(props) {

    super(props);
    this.state = {viewType:"1",
                  visible:false,
                  showNum:"5",
                  bgColor:"#ffffff",
                  title:"",
                  isCount:"0",
                  icon:"/spa/portal/images/defaultCustom/dbgz.png",
                  isSys:"1",
                  options:[],
                  data:[],
                  dbcount:"0",
                  bgTmd:"100",
                  setting:{
                     titleColor:'#000000',
                     textColor:'#000000',
                     textSpacing:20,
                     titleFontSize:'18',
                     textFontSize:'15',
                      isAutoReflush: '0',
                      reflushSpeed: 1
                  },
                  loading: false

         }}

    setStateData  = (data)=>{
        let setting = Object.assign({},this.state.setting,data)
        this.setState({setting:setting})
    }
    TitleOnChange= (value) => {
        this.setState({title:value});
    }

    ShowNumChnage = (value) => {
    this.setState({showNum: value});
    }

    changeViewType = (value) => {
        this.setState({viewType:value});
    }

    changebgColor = (value) => {
        this.setState({bgColor: value});
    }

    changeCount = (value) => {
        this.setState({isCount:value});
    }

    changeIcon = (value) => {
        this.setState({icon:value});
    }
    changeBgTmd = (value) => {
        this.setState({bgTmd:value});
    }

    handlerReflushModule = ()=>{
        this.setState({loading:true})
        this.getDatas();
    }


    getDatas = () => {
        WeaTools.callApi('/api/portal/wfsetting/customwf/getset','GET',{
            "id":this.props.id
        }).then((result) => {

            if(result.api_status==true&&result.isCz==true){
                let bg = result.setting.bgColor.split(',');

             this.setState({title:result.setting.title,
                 showNum:result.setting.shownum,viewType:result.setting.viewtype,
                 bgColor:bg[0],bgTmd:bg[1],icon:result.setting.icon,
                 isSys:result.isSys,
                 options:result.options,
                 data:result.datas,isCount:result.setting.isCount,setting:JSON.parse(result.setting.setting),loading: false});
             this.getDBWDS();
            }else if(result.api_status==true&&result.isCz==false){
                this.getDBWDS();
                this.setState({options:result.options,data:result.datas,loading: false});
            }
        })
    }

    getDBWDS = () =>{
        if(this.state.isCount=="1"){
            WeaTools.callApi('/api/workflow/reqlist/doingCountInfo','POST',{
                "typeids":"1"
            }).then((result) => {
              this.setState({dbcount: result.totalcount.flowNew});
            });
        }
    }

    componentWillReceiveProps(){
        this.getDatas();

    }

   componentDidMount(){
       this.getDatas();
       if(window.element_workflow_refresh){
           window.element_workflow_refresh[this.props.id] = this.handlerReflushModule
       }else{
           window.element_workflow_refresh = {}
           window.element_workflow_refresh[this.props.id] = this.handlerReflushModule
       }
       setTimeout(this.setReflushInterval,1000)

   }

   setReflushInterval = ()=>{
       if(this.state.setting.isAutoReflush == '1' && this.state.setting.reflushSpeed && this.state.setting.reflushSpeed >0){
           if(this.autoReflushInterval){
               clearInterval(this.autoReflushInterval)
           }
           this.autoReflushInterval = setInterval(this.getDatas,this.state.setting.reflushSpeed*60*1000)
       }

       if(this.state.setting.isAutoReflush == '0' && this.autoReflushInterval){
           clearInterval(this.autoReflushInterval)
       }
   }


    componentWillUnMount(){
        if(this.autoReflushInterval){
            clearInterval(this.autoReflushInterval)
        }

    }

   onCancel= ()=> {
    this.getDatas();
    this.setState({visible: false});
   }


   urlTiaozhuan = (item) =>{
        const url=item.requestname.link;
        const page = window.open(url);
        const reflushTimer = setInterval(()=>{
            if(page.closed){
                clearInterval(reflushTimer)
                window.element_workflow_reLoad()
            }
        },1000)
   }

   moreUrl = () => {
        const mores = [
            {"showNoReply":"1","isExclude":"2","perpage":"5","orderby":"","isall":"1","flowCount":"0","showView":"","showForward":"1","flowids":[],"showCopy":"1","showTimeout":"1","viewType":"1","showCY":"1","typeids":[],"fromhp":"1","nodeCount":0,"hpwhere":"","showReject":"1","typeCount":0,"nodeids":[]},
            {"showNoReply":"1","isExclude":"2","perpage":"5","orderby":"","isall":"1","flowCount":"0","showView":"","showForward":"1","flowids":[],"showTimeout":"0","viewType":"11","showCY":"1","typeids":[],"fromhp":"1","nodeCount":0,"hpwhere":"","showReject":"0","typeCount":0,"nodeids":[]},
            {"showNoReply":"1","isExclude":"2","perpage":"5","orderby":"","isall":"1","flowCount":"0","showView":"","showForward":"1","flowids":[],"showTimeout":"0","viewType":"12","showCY":"1","typeids":[],"fromhp":"1","nodeCount":0,"hpwhere":"","showReject":"0","typeCount":0,"nodeids":[]},
            {"showNoReply":"1","isExclude":"2","perpage":"5","orderby":"","isall":"1","flowCount":"0","showView":"","showForward":"1","flowids":[],"isArrangement":"1","showTimeout":"0","viewType":"2","showCY":"1","typeids":[],"fromhp":"1","nodeCount":0,"hpwhere":"","showReject":"0","typeCount":0,"nodeids":[]},
            {"showNoReply":"1","isExclude":"2","perpage":"5","orderby":"","isall":"1","flowCount":"0","showView":"","showForward":"1","flowids":[],"completeflag":"0","showTimeout":"0","viewType":"4","showCY":"1","typeids":[],"fromhp":"1","nodeCount":0,"hpwhere":"","showReject":"0","typeCount":0,"nodeids":[]},
            {"showNoReply":"1","isExclude":"2","perpage":"5","orderby":"","isall":"1","flowCount":"0","showView":"","showForward":"1","flowids":[],"showTimeout":"0","viewType":"3","showCY":"1","typeids":[],"fromhp":"1","nodeCount":0,"hpwhere":"","showReject":"0","typeCount":0,"nodeids":[]},
            {"showNoReply":"1","isExclude":"2","perpage":"5","orderby":"","isall":"1","flowCount":"0","showView":"","showForward":"1","flowids":[],"showTimeout":"0","viewType":"5","showCY":"1","typeids":[],"fromhp":"1","nodeCount":0,"hpwhere":"","showReject":"0","typeCount":0,"nodeids":[]},
            {"showNoReply":"1","isExclude":"2","perpage":"5","orderby":"","isall":"1","flowCount":"0","showView":"","showForward":"1","flowids":[],"showTimeout":"0","viewType":"6","showCY":"1","typeids":[],"fromhp":"1","nodeCount":0,"hpwhere":"","showReject":"0","typeCount":0,"nodeids":[]},
            {"showNoReply":"1","isExclude":"2","perpage":"5","orderby":"","isall":"1","flowCount":"0","showView":"","showForward":"1","flowids":[],"showTimeout":"0","viewType":"7","showCY":"1","typeids":[],"fromhp":"1","nodeCount":0,"hpwhere":"","showReject":"0","typeCount":0,"nodeids":[]},
            {"showNoReply":"0","isExclude":"2","perpage":"5","orderby":"","isall":"1","flowCount":"0","showView":"","showForward":"1","flowids":[],"showTimeout":"0","viewType":"13","showCY":"1","typeids":[],"fromhp":"1","nodeCount":0,"hpwhere":"","showReject":"0","typeCount":0,"nodeids":[]},
            {"showNoReply":"1","isExclude":"2","perpage":"5","orderby":"","isall":"1","flowCount":"0","showView":"","showForward":"1","flowids":[],"showTimeout":"0","viewType":"14","showCY":"1","typeids":[],"fromhp":"1","nodeCount":0,"hpwhere":"","showReject":"0","typeCount":0,"nodeids":[]},
            {"showNoReply":"1","isExclude":"2","perpage":"5","orderby":"","isall":"1","flowCount":"0","showView":"","showForward":"1","flowids":[],"showTimeout":"0","viewType":"10","showCY":"1","typeids":[],"fromhp":"1","nodeCount":0,"hpwhere":"","showReject":"0","typeCount":0,"nodeids":[]},
            {"showNoReply":"1","isExclude":"2","perpage":"5","orderby":"","isall":"1","flowCount":"0","showView":"","showForward":"1","flowids":[],"showTimeout":"0","viewType":"8","showCY":"1","typeids":[],"fromhp":"1","nodeCount":0,"hpwhere":"","showReject":"0","typeCount":0,"nodeids":[]}
        ]
        let more = ""
        for(let i = 0 ;i< mores.length ;i++){
            if(mores[i].viewType == this.state.viewType){
                more = mores[i]
                if(mores[i].viewType ==6){
                    window.open("/spa/workflow/index_mobx.jsp#/main/workflow/supervise?fromwhere=jsonFilter&jsonstr="+'&eid=portal_ts_old_workflow'+this.state.viewType+'&tabid=1&tabTitle='+Base64.encodeURI(this.state.title));
                }else{
                    window.open("/spa/workflow/index_mobx.jsp#/main/workflow/queryFlowResult?fromwhere=jsonFilter&jsonstr="+'&eid=portal_ts_old_workflow'+this.state.viewType+'&tabid=1&tabTitle='+Base64.encodeURI(this.state.title));
                }

            }
        }

   }

   settingDia = () => {
       this.setState({visible:true});
   }

    changeHx = () => {

        let tmd = parseInt(this.state.bgTmd);
        if(tmd=='NaN'){
            tmd = 100;
        }
        const hxtmd = parseInt((tmd/100)*255);

        let temp = hxtmd.toString(16);
        if(hxtmd<10){
            temp ="0"+ temp;
        }
        return temp;

    }

   saveSetting= () =>{

       WeaTools.callApi('/api/portal/wfsetting/customwf/saveset','POST',{
           jsonStr: JSON.stringify({"title":this.state.title,
               "shownum":this.state.showNum,
               "viewtype":this.state.viewType,
               "bgColor":this.state.bgColor+","+this.state.bgTmd,
               "isCount":this.state.isCount,
               "icon":this.state.icon,
               "id":this.props.id,
               "setting":JSON.stringify(this.state.setting)
           })
       }).then(result => {
           if(result.api_status==true){
               this.setState({visible:false});
               message.success(getLabel(83551,"保存成功！"),2);
               this.getDatas();
               setTimeout(this.setReflushInterval,1000)
           }else {
               message.error(getLabel(84544,"保存失败！"),2);
           }
       })
   }

   handlerImageLoadChangeSize = (currentTarget)=>{
        let width = $(currentTarget).width()
        let height = $(currentTarget).height()
        if(width > 50 || height > 50){
            if(width > height){
                $(currentTarget).width(50)
            }else{
                $(currentTarget).height(50)
            }
        }
   }


   getOverTime = (createDate,createTime)=>{
        const currentDate = new Date();

        var dateString = createDate+" "+createTime;

       const  now=new Date().getTime();   //获取当前时间毫秒
       var minute=1000*60;      //把分，时，天，周，半个月，一个月用毫秒表示
       var hour=minute*60;
       var day=hour*24;
       var week=day*7;
       var month=day*30;
       var year =  month*12

       // var arr1 = dateString.split(" ");
       // var sdate = arr1[0].split('-');
       // const dateStringdate = new Date(sdate[0], sdate[1]-1, sdate[2]).getTime();

       dateString = dateString.replace(/-/g,"/");
       const dateStringdate = new Date(dateString);

       var diffValue=now-dateStringdate;//时间差
       var  minC=diffValue/minute;  //计算时间差的分，时，天，周，月
       var  hourC=diffValue/hour;
       var  dayC=diffValue/day;
       var  weekC=diffValue/week;
       var  monthC=diffValue/month;
       var  yearC=diffValue/year;
       let result = ""

        if(diffValue>year){
           result=" "+parseInt(yearC)+"年前"
       }else if(diffValue>month){
           result=" "+parseInt(monthC)+"月前"
       }else if(diffValue>week){
           result=" "+parseInt(weekC)+"周前"
       }else if(diffValue>day){
           result=" "+parseInt(dayC)+"天前"
       }else if(diffValue>hour){
           result=" "+parseInt(hourC)+"小时前"
       }else if(diffValue>minute){
           result=" "+parseInt(minC)+"分钟前"
       }else{
           result="刚到";
       } 

       //  const year = currentDate.getFullYear()
       //  const month = currentDate.getMonth()+1 < 10 ? '0'+(currentDate.getMonth()+1) : currentDate.getMonth()+1
       //  const date = currentDate.getDate() < 10 ? '0'+currentDate.getDate():currentDate.getDate()
       // const ymd = year +"-"+ month +"-"+date
       //  const hour = currentDate.getHours()<10 ? '0'+currentDate.getHours():currentDate.getHours()
       //  const minute = currentDate.getMinutes() < 10 ? '0'+ currentDate.getMinutes(): currentDate.getMinutes();
       //  const second = currentDate.getSeconds()< 10  ? '0' +currentDate.getSeconds() : currentDate.getSeconds()
       //  const hms = hour +":"+minute +":"+second
       //  let result = ""
       //  if(createDate && createDate!="" && createTime || createTime !=""){
       //      let dates = createDate.split("-")
       //      let times = createTime.split(":")
       //      if(createDate == ymd){
       //          if(hms == createTime){
       //              result = "刚到"
       //          }else{
       //              if(hour != times[0]){
       //                  result = (parseInt(hour)-parseInt(times[0]))+"小时前"
       //              }else if(minute != times[1]){
       //                  result = (parseInt(minute)-parseInt(times[1]))+"分钟前"
       //              }else if(second != times[2]){
       //                  result = (parseInt(second)-parseInt(times[2]))+"秒前"
       //              }
       //          }
       //      }else{
       //          if(year != dates[0]){
       //              result = (parseInt(year)-parseInt(dates[0]))+"年前"
       //          }else if(month != dates[1]){
       //              result =  (parseInt(month)-parseInt(dates[1]))+"月前"
       //          }else if(date != dates[2]){
       //              result =  (parseInt(date)-parseInt(dates[2]))+"天前"
       //          }
       //      }
       //  }
        return result

   }

    colorToRGB() {
        let color = this.state.bgColor
        let tmd = parseInt(this.state.bgTmd)/100;
        var color1, color2, color3;
        color = ""+color;
        if (typeof color !== "string") return;
        if (color.charAt(0) == "#") {
            color = color.substring(1);
        }
        var not16num = color.split("").filter(function (item, index) {
            return isNaN(parseInt(item, 16))
        });
        if(not16num.length) return;
        switch (color.length) {
            case 3:
                color1 = color.substr(0,1);
                color2 = color.substr(1,1);
                color3 = color.substr(2,1);
                color1 = color1 + color1;
                color2 = color2 + color2;
                color3 = color3 + color3;
                break;
            case 6:
                color1 = color.substr(0,2);
                color2 = color.substr(2,2);
                color3 = color.substr(4,2);
                break;
            default:
                return false;
        }
        color1 = parseInt(color1, 16);
        color2 = parseInt(color2, 16);
        color3 = parseInt(color3, 16);
        return "rgba("+color1+","+color2+","+color3+","+tmd+")";
    }

    render() {
     const data=this.state.data;
     const {visible,isSys,dbcount,viewType,bgColor,bgTmd,setting,loading} = this.state;
     const {titleColor,textColor,textSpacing,titleFontSize,textFontSize,batchHandlerUrl} = setting
        let isCount = {};
        isCount = {display:"none"};
     if(this.state.isCount!="0"&&viewType=="1"){
         isCount = {};
     }

        const bgcolor = this.colorToRGB()
        let display ="";
        if(this.props.isSetting==false){
            display="none";
        }
        return (
            <div className="portal-com-dbgz" style={{"background-color":bgcolor}}>
                <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@m64crj`}  className="dbgz-setting-icon" onClick={this.settingDia} type="setting" theme="filled" style={{"display":display}}/>
                <div className="portal-com-dbgz-count" style={isCount}>{dbcount}</div>
                <div className="portal-com-dbgz-content">
                    <div className="portal-com-dbgz-header">
                        {
                            this.state.icon ? (
                                <div style={{height:"50px",float:"left"}}>
                                    <img  src={this.state.icon} style={{'vertical-align':'middle'}}  onLoad={(e)=>{this.handlerImageLoadChangeSize(e.currentTarget)}}/>
                                    <div style={{display:'inline-block',height:'100%','vertical-align':'middle'}}></div>
                                </div>
                            ) :(
                              ""
                            )
                        }


                        <span className="portal-com-dbgz-title" style={{ width: 100, height: 50,"line-height": 50, display: "inline-block",color:titleColor,'font-size':titleFontSize}}>{this.state.title}</span>
                        <img style={{position:'absolute',top:'24px',right:'160px',cursor:'pointer'}} src={lb} onClick={()=>{window.open(batchHandlerUrl,'_blank')}}/>
                        <img style={{position:'absolute',top:'24px',right:'125px',cursor:'pointer'}}  src={reflush} onClick={this.handlerReflushModule}/>
                        <img style={{position:'absolute',top:'24px',right:'90px',cursor:'pointer'}} src={add} onClick={()=>{window.open('/spa/workflow/static/index.html#/main/workflow/add','_blank')}}/>
                        <span className="portal-com-dbgz-more"   style={{"font-size":12}} >
                            <span onClick={this.moreUrl} style={{color:titleColor}}>{getLabel(17499,"更多")}  &gt;</span>
                        </span>
                    </div>
                    <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@2daf7h`} spinning={loading}>
                        {
                            data.length>0 ? (
                            <div className="portal-com-dbgz-data">
                                <ul>
                                    {
                                        data.map((item) => {
                                            return (
                                                <li className="portal-com-dbgz-data-item-li" style={{cursor:'pointer','margin-bottom':textSpacing+'px'}} onClick={() => this.urlTiaozhuan(item)}>
                                                    <span style={{display: 'inline-block','width':'70%'}}>
                                                        <span title={$(`<div>${item.requestname.pretitle+ item.requestname.name}</div>`).text()} style={{color:textColor,'font-size':textFontSize,'max-width':'calc(100% - 10px)','overflow':'hidden','text-overflow':'ellipsis','white-space':'nowrap',display:'inline-block'}} dangerouslySetInnerHTML={{ __html: item.requestname.pretitle+ item.requestname.name }}></span>
                                                        <span style={{width:'10px','text-align':'center',display:'inline-block','vertical-align':'top'}}>
                                                            {
                                                                item.requestname.img ? <img src={item.requestname.img} style={{'vertical-align':'middle'}}/> : ''
                                                            }
                                                        </span>

                                                    </span>
                                                    <span style={{width:'13%','overflow':'hidden','text-overflow':'ellipsis','white-space':'nowrap',color:'#cccccc',display:'inline-block','text-align':'center','font-size':textFontSize}}>{this.getOverTime(item.createdate,item.createtime)}</span>

                                                    <span style={{width:'17%','overflow':'hidden','text-overflow':'ellipsis','white-space':'nowrap',color:'#666666',display:'inline-block','text-align':'center','font-size':textFontSize}} title={item.createdate}>{item.createdate}</span>
                                                </li>
                                            );
                                        })
                                    }
                                </ul>
                            </div>
                            ):(
                               ""
                            )
                        }
                        {
                            data.length == 0?(
                                <div className="portal-com-dbgz-data">
                                    <ul  style={{color:textColor,"font-size":textFontSize}}>
                                        {getLabel(83553,"暂无数据")}
                                    </ul>
                                </div>
                            ):""

                        }
                    </Spin>
                </div>
                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@2opzi7`} visible={visible} onCancel={this.onCancel} title={getLabel(30747,"设置")}>
                    <div style={{position:"relative",height:400}}>
                        <div style={{height: '350px','overflow-y':'auto'}}>
                         <Setting_Tab ecId={`${this && this.props && this.props.ecId || ''}_Setting_Tab@lq9t00`}  titleChange={this.TitleOnChange}  ShowNumChnage={this.ShowNumChnage}  changeBgTmd={this.changeBgTmd} changeViewType={this.changeViewType} changebgColor={this.changebgColor} changeCount={this.changeCount} changeIcon={this.changeIcon} settingInfo={this.state} setStateData={this.setStateData} />
                        </div>
                        <div style={{position:"absolute",bottom:7,"margin-left": "67%"}}>
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@eicalh`} onClick={this.saveSetting} type="primary">{getLabel(33703,"确认")}</Button>
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@a74sy6`} onClick={this.onCancel} style={{"margin-left":10}}>{getLabel(31129,"取消")}</Button>
                        </div>
                    </div>
                </WeaDialog>
            </div>
        );
    }
}

//流程元素全局刷新方法
window.element_workflow_reLoad = function(){
    if(window.element_workflow_refresh  && typeof window.element_workflow_refresh == 'object'){
        for(let id in element_workflow_refresh){
            if(typeof element_workflow_refresh[id] == 'function'){
                element_workflow_refresh[id]();
            }
        }
    }
}

export default Dbgz;